<template>
  <view class="custom-tab-bar">
    <view 
      v-for="(item, index) in tabList" 
      :key="index" 
      class="tab-item"
      :class="{ active: activeIndex === index }"
      @click="switchTab(index, item.pagePath)"
    >
      <image 
        :src="activeIndex === index ? item.selectedIconPath : item.iconPath" 
        class="tab-icon"
      />
      <text class="tab-text">{{ item.text }}</text>
    </view>
  </view>
</template>

<script>
export default {
  name: 'CustomTabBar',
  data() {
    return {
      activeIndex: 0,
      tabList: [
        {
          text: "首页",
          pagePath: "pages/index/index",
          iconPath: "/static/tabbar/index.png",
          selectedIconPath: "/static/tabbar/index_check.png"
        },
        {
          text: "数据",
          pagePath: "pages/msg/msg",
          iconPath: "/static/tabbar/msg.png",
          selectedIconPath: "/static/tabbar/msg_check.png"
        },
        {
          text: "打卡",
          pagePath: "pages/checkin/checkin",
          iconPath: "/static/tabbar/check.png",
          selectedIconPath: "/static/tabbar/checked.png"
        },
        {
          text: "我的",
          pagePath: "pages/my/my",
          iconPath: "/static/tabbar/my.png",
          selectedIconPath: "/static/tabbar/my_checked.png"
        }
      ]
    }
  },
  mounted() {
    // 获取当前页面路径，设置激活的 tab
    this.updateActiveTab();
    
    // 监听页面显示事件
    uni.$on('onShow', () => {
      this.updateActiveTab();
    });
  },
  
  beforeDestroy() {
    // 移除事件监听
    uni.$off('onShow');
  },
  
  methods: {
    updateActiveTab() {
      // 使用 setTimeout 确保在页面切换完成后获取正确的页面路径
      setTimeout(() => {
        // 获取当前页面路径，设置激活的 tab
        const pages = getCurrentPages();
        if (pages.length > 0) {
          const currentPage = pages[pages.length - 1];
          const route = currentPage.route;
          
          console.log('Current page route:', route);
          
          // 根据当前页面路径设置激活的 tab
          const index = this.tabList.findIndex(item => item.pagePath === route);
          if (index !== -1) {
            this.activeIndex = index;
          }
        }
      }, 50); // 延迟50ms确保页面切换完成
    },
    
    switchTab(index, path) {
      console.log('Switching to tab:', index, path);
      // 切换页面
      uni.switchTab({
        url: '/' + path
      });
    }
  }
}
</script>

<style scoped>
.custom-tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 90px; /* 可根据需要调整 */
  background-color: #2e2f34; /* 与原配置一致 */
  display: flex;
  justify-content: space-around;
  align-items: center;
  z-index: 999; /* 确保在最上层 */
}

.tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  flex: 1;
}

.tab-icon {
  width: 20px;
  height: 20px;
}


.tab-text {
  font-size: 12px;
  color: #fff; /* 与原配置一致 */
}

.tab-item.active .tab-text {
  color: #ecf005; /* 与原配置一致 */
}
</style>